package com.depin.pdaapp.http;


import com.depin.pdaapp.constant.Constant;
import com.depin.pdaapp.utils.ApplicationHelper;
import com.google.gson.Gson;
import com.jaydenxiao.common.basebean.BaseRespose;
import com.jaydenxiao.common.baserx.DataFormatException;
import com.jaydenxiao.common.baserx.ServerException;
import com.jaydenxiao.common.commonutils.SPUtils;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;


/**
 * Created by Administrator on 2017/4/30.
 */

public class GsonResponseBodyConverter implements Converter<ResponseBody, BaseRespose> {
    private final Gson gson;
    private final Type type;


    public GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }


    @Override
    public BaseRespose convert(ResponseBody value) throws IOException {
        String response = value.string();
        BaseRespose httpResult = null;
        //先将返回的json数据解析到Response中，如果code==200，则解析到我们的实体基类中，否则抛异常
        try {
            httpResult = gson.fromJson(response, type);
        } catch (Exception e) {
            throw new DataFormatException("数据格式错误");
        }
        if (httpResult.getCode()==200) {
            //0的时候就直接解析，不可能出现解析异常。因为我们实体基类中传入的泛型，就是数据成功时候的格式
            return httpResult;
        } else {
            throw new ServerException(httpResult.getMsg());
        }
    }
}